local skynet = require "skynet"
require "skynet.manager"
local configdao = require "configdao"
local string = string
local table_insert = table.insert
local table_remove = table.remove
local filelog = require "filelog"
local timetool = require "timetool"
local tabletool = require "tabletool"

local CMD = {}
local msgpool = {}
local TIME_LEN = 5
local router = {}
local popconfig = {}

local queue = require "skynet.queue"
local cs = queue()

local function send_popmessage(data)
    if not data then return end
    local msgbody = {}
    if type(data[1]) == type(0) then
        local popmsg = popconfig[data[1]]
        if popmsg then
            msgbody.msg = popmsg
            if data[2] then
                msgbody.msg = string.gsub(msgbody.msg, "_MNAME_", data[2].minename)
                msgbody.msg = string.gsub(msgbody.msg, "_ONAME_", data[2].othername)
            end
        end
    elseif type(data[1]) == type'' then -- 支持发送确定的字符串
        msgbody.msg = data[1]
    end
    local agents = skynet.call(".mainnode", "lua", "cmd", "get_all_agents")
    if agents then
        for rid, agent in pairs(agents) do
            skynet.send(agent.agent, "lua", "cmd", "notify_client", "popmessageN", msgbody)
        end
    end
end

local function check_popmessage()
    local status, msg
    while true do
        status, msg = pcall(send_popmessage, table_remove(msgpool, 1))
        if not status then
            filelog.sys_error("check_popmessage pcall error!", status, msg)
        end
        --挂起一段时间，然后继续检测
        skynet.sleep(TIME_LEN * 100)
    end
end

local function insert_message(msg)
    table_insert(msgpool, msg)
end

-- 添加全服广播消息（道具使用等）
    -- idx number时，为消息配置idx（gate的config_node配置里）；string时，为确定的字符串
    -- data 玩家数据 = {minename = '', othername = ''}
function CMD.addpopmessage(idx, data)
    cs(insert_message, {idx, data})
end

function CMD.init(caller)
    router = caller -- 这里的caller，是router
    popconfig = tabletool.deepcopy(configdao.get_common_conf("popconfig"))   --初始化广播消息格式配置
    skynet.fork(check_popmessage)
end

return CMD